💯 solving-algo | February 17, 2021
import sys
n = int(sys.stdin.readline())
stack = [0]
for i in range(n):
input = sys.stdin.readline().split()
if input[0] == "push":
stack.append(int(input[1]))
elif input[0] == "top":
if len(stack) == 1:
print(-1)
else:
print(stack[-1])
elif input[0] == "size":
if len(stack) == 1:
print(0)
else:
print(len(stack)-1)
elif input[0] == "empty":
if len(stack) == 1:
print(1)
else:
print(0)
elif input[0] == "pop":
if len(stack) == 1:
print(-1)
else:
print(stack[-1])
if len(stack) == 1:
pass
else:
stack.pop()
IndexError
방지를 위한 초기에0
index 추가
import sys
n = int(sys.stdin.readline())
stack = [0]
for i in range(n):
input = int(sys.stdin.readline())
stack.append(input)
if input == 0:
if len(stack) == 1:
pass
# 위에서 input 값이 0일 경우에도 삽입하기 때문에(append) pop를 두번 해줬다.
else:
stack.pop()
stack.pop()
print(sum(stack))
import sys
n = int(sys.stdin.readline())
for i in range(n):
input = sys.stdin.readline().rstrip()
stack = [0]
for j in input:
if j == "(":
stack.append(j)
else:
try:
stack.pop()
except:
continue
if len(stack) == 1:
if stack[0] == "(":
print("NO")
else:
print("YES")
else:
print("NO")
import sys
input = sys.stdin.readline
while 1:
string = input().rstrip()
stack = []
true_flag = 1
for cha in string:
if cha == '(' or cha == '[':
stack.append(cha)
elif cha == ')':
if stack and stack[-1] == '(':
stack.pop()
else:
true_flag = 0
break
elif cha == ']':
if stack and stack[-1] == '[':
stack.pop()
else:
true_flag = 0
break
if string == '.':
break
print("yes" if true_flag and not(stack) else "no")